package org.fengfei.wanmonitor;

import java.util.Timer;
import java.util.TimerTask;

public class UpdateDDNSByAli {
	
	private final AliYunUtil aliYunUtil;
	private final Timer timer;

	public UpdateDDNSByAli(String accessKeyId, String accessKeySecret) {
		this.aliYunUtil = new AliYunUtil(accessKeyId, accessKeySecret);
		this.timer = new Timer();
	}

	public void startMonitor(final String configDomain, final String domainRecordId, final String rR, final long cycle) {
		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				updateIPforDomainRecord(configDomain, domainRecordId, rR);
			}
		}, 0, cycle);
	}

	private void updateIPforDomainRecord(String configDomain, String domainRecordId, String rR) {
		String ipDomain = InternetUtil.getIPByDomain(rR + "." + configDomain);
		System.out.println("ipDomain=" + ipDomain);
		String ipWan = InternetUtil.getInternetIp();
		System.out.println("ipWan=" + ipWan);
		if (!ipWan.equals(ipDomain)) {
			aliYunUtil.updateATypeDomainRecord(domainRecordId, ipWan, rR);
		}
	}

	public void stopMonitor() {
		timer.cancel();
	}

}
